﻿// <copyright file="Database.cs" company="Hallvard Korsgaard">
//  Microsoft Public License (Ms-PL). See license details here: http://enoceannet.codeplex.com/license
// </copyright>
// <author>Hallvard Korsgaard</author>

namespace Logger
{
  using System;
  using System.Configuration;
  using System.Data;
  using System.Data.SqlClient;
  using EnOcean;
  using EnOcean.Radio.Sensor;

  /// <summary>
  /// Wrapper methods for SQL Server stored procedures.
  /// </summary>
  internal static class Database
  {
   
    /// <summary>
    /// Calls the StoreSensorTelegram stored procedure.
    /// </summary>
    /// <param name="telegram">The EnOcean telegram to store.</param>
    /// <param name="created">The time the event occurred.</param>
    internal static void StoreSensorTelegram(SensorTelegram telegram, DateTimeOffset created)
    {
      SqlConnection con;
      SqlCommand cmd;
      byte[] raw;

      raw = telegram.GetBytes();

      using (con = new SqlConnection(GetConnectionString()))
      {
        con.Open();

        using (cmd = new SqlCommand("StoreSensorTelegram", con))
        {
          cmd.CommandType = CommandType.StoredProcedure;

          cmd.Parameters.Add(new SqlParameter("@SensorId", SqlDbType.BigInt)
          {
            Value = telegram.Id
          });


          cmd.Parameters.Add(new SqlParameter("@HSEQ", SqlDbType.TinyInt)
          {
            Value = raw[2]
          });

          cmd.Parameters.Add(new SqlParameter("@ORG", SqlDbType.TinyInt)
          {
            Value = raw[3]
          });

          cmd.Parameters.Add(new SqlParameter("@Data0", SqlDbType.TinyInt)
          {
            Value = raw[7]
          });

          cmd.Parameters.Add(new SqlParameter("@Data1", SqlDbType.TinyInt)
          {
            Value = raw[6]
          });

          cmd.Parameters.Add(new SqlParameter("@Data2", SqlDbType.TinyInt)
          {
            Value = raw[5]
          });

          cmd.Parameters.Add(new SqlParameter("@Data3", SqlDbType.TinyInt)
          {
            Value = raw[4]
          });

          cmd.Parameters.Add(new SqlParameter("@Status", SqlDbType.TinyInt)
          {
            Value = raw[12]
          });


          cmd.Parameters.Add(new SqlParameter("@Created", SqlDbType.DateTimeOffset)
          {
            Value = created
          });

          cmd.ExecuteNonQuery();
        }

        con.Close();
      }
    }

    /// <summary>
    /// Reads the connection string from the config file.
    /// </summary>
    /// <returns>The connection string.</returns>
    private static string GetConnectionString()
    {
      return ConfigurationManager.ConnectionStrings["LogDatabase"].ConnectionString;
    }
  }
}
